﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace L.EntityFramework
{
    public abstract class BaseContext : DbContext
    {
        public string ConnectionString { get; set; }
        public BaseContext(string _connectionName)
            : base(_connectionName)
        {
            ConnectionString = Database.Connection.ConnectionString;
            // 是否启动延迟加载
            Configuration.LazyLoadingEnabled = false;
            // 是否启动代理
            Configuration.ProxyCreationEnabled = false;
            Configuration.AutoDetectChangesEnabled = false;
            Configuration.ValidateOnSaveEnabled = false;
            // 防止Entity变更导致数据库自动更新
            Database.SetInitializer<BaseContext>(null);
            //Database.Log = SqlLog;
        }

        //public void SqlLog(string sql)
        //{
        //    var _setting = System.Configuration.ConfigurationManager.AppSettings["_EF_Database_Log"];
        //    var _path = AppDomain.CurrentDomain.BaseDirectory + @"_EF_Database_Log\";
        //    if (_setting == "true")
        //    {
        //        Task.Run(() =>
        //        {
        //            if (!System.IO.Directory.Exists(_path))
        //            {
        //                System.IO.Directory.CreateDirectory(_path);
        //            }

        //            if (string.IsNullOrWhiteSpace(sql)) return;

        //            if (sql.Contains("关闭了连接"))
        //            {
        //                System.IO.File.AppendAllLines(_path + DateTime.Today.ToString("yyyy-MM-dd") + ".txt",
        //                    new string[] { sql, "-END-", "" });
        //            }
        //            else
        //            {
        //                System.IO.File.AppendAllLines(_path + DateTime.Today.ToString("yyyy-MM-dd") + ".txt",
        //                    new string[] { sql });
        //            }
        //        });
        //    }
        //}

    }
}
